<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getActivityList, 
  getActivityDetail, 
  createActivity, 
  updateActivity, 
  deleteActivity, 
  getActivityParticipants,
  updateActivityStatus
} from '@/api/activity'
import { uploadFile, deleteFile, getImageUrl } from '@/api/file'
import request from '@/utils/request'

// 活动列表数据
const activityList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchForm = reactive({
  keyword: '',
  status: ''
})

// 活动表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增活动')
const activityForm = reactive({
  id: null,
  title: '',
  description: '',
  content: '',
  startTime: '',
  endTime: '',
  location: '',
  maxParticipants: 50,
  status: 1,
  cover: ''
})
const activityFormRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { max: 50, message: '标题最多50个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大参与人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '人数必须大于0', trigger: 'blur' }
  ]
}
const activityFormRef = ref(null)

// 图片上传相关
const imageUrl = ref('')
const dialogImageUrl = ref('')
const dialogImageVisible = ref(false)

// 参与者列表对话框
const participantsDialogVisible = ref(false)
const currentActivityId = ref(null)
const currentActivityTitle = ref('')
const participantsList = ref([])
const participantsLoading = ref(false)

// 页面加载时获取活动列表
onMounted(() => {
  loadActivityList()
})

// 加载活动列表
const loadActivityList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    const res = await getActivityList(params)
    if (res.code === 200) {
      activityList.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表出错', error)
    ElMessage.error('获取活动列表失败，请稍后重试')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadActivityList()
}

// 处理重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadActivityList()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadActivityList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadActivityList()
}

// 图片上传相关方法
const handleImageSuccess = (response) => {
  // 处理服务器返回的图片URL
  console.log('上传成功响应:', response)
  if (response.code === 200) {
    // 获取图片相对路径并处理
    const relativePath = response.data
    // 生成完整的图片URL
    const fullImageUrl = getImageUrl(relativePath)
    
    imageUrl.value = fullImageUrl
    activityForm.cover = relativePath // 保存相对路径到表单中
  } else {
    ElMessage.error(response.message || '图片上传失败')
  }
}

// 添加上传前验证方法
const beforeAvatarUpload = (file) => {
  console.log('准备上传文件:', file.name, file.type, file.size)
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 添加headers，确保token正确传递
const getUploadHeaders = () => {
  return {
    Authorization: `Bearer ${localStorage.getItem('token')}`
  }
}

// const handleImagePreview = (file) => {
//   dialogImageUrl.value = file.url || URL.createObjectURL(file.raw)
//   dialogImageVisible.value = true
// }

// const handleImageRemove = () => {
//   // 如果有图片URL，则调用删除API
//   if (imageUrl.value && imageUrl.value.includes('http')) {
//     deleteFile(imageUrl.value)
//       .then(res => {
//         if (res.code === 200) {
//           ElMessage.success('图片删除成功')
//         }
//       })
//       .catch(err => {
//         console.error('删除图片出错', err)
//       })
//   }
  
//   // 无论删除API是否成功，都清空本地的图片URL值
//   imageUrl.value = ''
//   activityForm.cover = ''
// }

// 查看活动图片
const handleViewImage = (url) => {
  dialogImageUrl.value = getImageUrl(url)
  console.log(dialogImageUrl.value)
  dialogImageVisible.value = true
}

// 打开新增活动对话框
const handleAdd = () => {
  dialogTitle.value = '新增活动'
  activityForm.id = null
  activityForm.title = ''
  activityForm.description = ''
  activityForm.content = ''
  activityForm.startTime = ''
  activityForm.endTime = ''
  activityForm.location = ''
  activityForm.maxParticipants = 50
  activityForm.status = 1
  activityForm.cover = ''
  imageUrl.value = ''
  dialogVisible.value = true
}

// 打开编辑活动对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑活动'
  activityForm.id = row.id
  activityForm.title = row.title
  activityForm.description = row.description || ''
  activityForm.content = row.content || ''
  activityForm.startTime = row.startTime
  activityForm.endTime = row.endTime
  activityForm.location = row.location
  activityForm.maxParticipants = row.maxParticipants
  activityForm.status = row.status
  activityForm.cover = row.cover
  imageUrl.value = getImageUrl(row.cover)
  dialogVisible.value = true
}

// 提交活动表单
const submitActivityForm = async () => {
  activityFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (activityForm.id) {
          // 编辑活动
          const res = await updateActivity(activityForm)
          if (res.code === 200) {
            ElMessage.success('更新活动成功')
            dialogVisible.value = false
            loadActivityList()
          } else {
            ElMessage.error(res.message || '更新活动失败')
          }
        } else {
          // 新增活动
          const res = await createActivity(activityForm)
          if (res.code === 200) {
            ElMessage.success('创建活动成功')
            dialogVisible.value = false
            loadActivityList()
          } else {
            ElMessage.error(res.message || '创建活动失败')
          }
        }
      } catch (error) {
        console.error('提交活动表单出错', error)
        ElMessage.error('操作失败，请稍后重试')
      }
    } else {
      return false
    }
  })
}

// 查看活动详情
const handleDetail = async (row) => {
  try {
    const res = await getActivityDetail(row.id)
    if (res.code === 200) {
      const activity = res.data.activity
      
      ElMessageBox.alert(
        `
        <p><strong>标题：</strong>${activity.title}</p>
        <p><strong>描述：</strong>${activity.description || ''}</p>
        <p><strong>开始时间：</strong>${activity.startTime}</p>
        <p><strong>结束时间：</strong>${activity.endTime}</p>
        <p><strong>地点：</strong>${activity.location}</p>
        <p><strong>参与人数：</strong>${activity.currentParticipants}/${activity.maxParticipants}</p>
        <p><strong>状态：</strong>${activity.status === 1 ? '已发布' : activity.status === 0 ? '草稿' : '已结束'}</p>
        <p><strong>创建时间：</strong>${activity.createTime}</p>
        ${activity.cover ? `<p><strong>活动图片：</strong><br/><img src="${getImageUrl(activity.cover)}" style="max-width: 100%; max-height: 300px; margin-top: 10px;" /></p>` : ''}
        `,
        '活动详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: () => {}
        }
      )
    } else {
      ElMessage.error(res.message || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情出错', error)
    ElMessage.error('获取活动详情失败，请稍后重试')
  }
}

// 查看参与者列表
const handleViewParticipants = async (row) => {
  currentActivityId.value = row.id
  currentActivityTitle.value = row.title
  participantsLoading.value = true
  participantsList.value = []
  participantsDialogVisible.value = true
  
  try {
    const res = await getActivityParticipants(row.id)
    if (res.code === 200) {
      participantsList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取参与者列表失败')
    }
  } catch (error) {
    console.error('获取参与者列表出错', error)
    ElMessage.error('获取参与者列表失败，请稍后重试')
  } finally {
    participantsLoading.value = false
  }
}

// 处理活动状态更新
const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '发布' : '下架'
  
  ElMessageBox.confirm(
    `确认要${statusText}该活动吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await updateActivityStatus(row.id, newStatus)
        if (res.code === 200) {
          ElMessage.success(`${statusText}成功`)
          loadActivityList()
        } else {
          ElMessage.error(res.message || `${statusText}失败`)
        }
      } catch (error) {
        console.error('更新活动状态出错', error)
        ElMessage.error(`${statusText}失败，请稍后重试`)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 处理删除活动
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该活动吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await deleteActivity(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadActivityList()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除活动出错', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 格式化活动状态
const formatStatus = (status) => {
  const statusMap = {
    0: '草稿',
    1: '已发布',
    2: '已结束'
  }
  return statusMap[status] || '未知状态'
}
</script>

<template>
  <div class="activity-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>活动管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="活动标题/描述"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 100px;">
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已结束" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd">新增活动</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="activityList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column label="活动图片" width="100">
          <template #default="scope">
            <el-image 
              v-if="scope.row.cover"
              :src="getImageUrl(scope.row.cover)" 
              style="width: 80px; height: 60px; object-fit: cover; cursor: pointer;"
              @click="handleViewImage(scope.row.cover)"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="location" label="地点" width="120" show-overflow-tooltip />
        <el-table-column label="参与人数" width="100">
          <template #default="scope">
            {{ scope.row.currentParticipants }}/{{ scope.row.maxParticipants }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="
              scope.row.status === 0 ? 'info' :
              scope.row.status === 1 ? 'success' : 'warning'
            ">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="260">
          <template #default="scope">
            <el-button
              type="info"
              size="small"
              @click="handleDetail(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleViewParticipants(scope.row)"
            >
              参与者
            </el-button>
            <el-button
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              size="small"
              @click="handleStatusChange(scope.row)"
              :disabled="scope.row.status === 2"
            >
              {{ scope.row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 活动表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityFormRules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="activityForm.title"
            placeholder="请输入活动标题"
          />
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input
            v-model="activityForm.location"
            placeholder="请输入活动地点"
          />
        </el-form-item>
        <el-form-item label="最大人数" prop="maxParticipants">
          <el-input-number
            v-model="activityForm.maxParticipants"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动图片">
          <el-upload
            class="activity-image-uploader"
            :action="`http://localhost:80/api/file/upload`"
            :headers="getUploadHeaders()"
            :data="{ type: 'activity' }"
            name="file"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :on-error="(err, file) => { 
              console.error('上传失败', err);
              // 尝试解析错误消息
              let errorMsg = '上传失败，请重试';
              try {
                if (typeof err.message === 'string') {
                  errorMsg = err.message;
                } else if (err.status === 401) {
                  errorMsg = '未授权，请重新登录';
                } else if (typeof err === 'string') {
                  errorMsg = err;
                }
              } catch (e) {}
              ElMessage.error(errorMsg);
            }"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <img v-if="imageUrl" :src="imageUrl" class="activity-image" />
            <el-icon v-else class="activity-image-uploader-icon"><Plus /></el-icon>
          </el-upload>

          <div class="el-upload__tip">
            图片格式：JPG/PNG/GIF，不超过2MB
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="activityForm.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitActivityForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 参与者列表对话框 -->
    <el-dialog
      v-model="participantsDialogVisible"
      :title="`参与者列表 - ${currentActivityTitle}`"
      width="500px"
    >
      <el-table :data="participantsList"  border>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="registerTime" label="报名时间" width="160" />
      </el-table>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="dialogImageVisible" title="图片预览">
      <img :src="dialogImageUrl" alt="预览图片" style="width: 100%;" />
    </el-dialog>
  </div>
</template>

<style scoped>
.activity-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.activity-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: inline-block;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.activity-image-uploader:hover {
  border-color: #409EFF;
}

.activity-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.activity-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style> 